package br.com.engine.input;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.Vector;

import br.com.engine.controle.Tela;

public class TecladoAdapter extends KeyAdapter
{
    private static List<TecladoAdapter> lInstancias = new Vector<TecladoAdapter>( );
    
	private List<EventoTecla> lEventos      = new Vector<EventoTecla>( );
	private List<Action>      acoesPressed  = new Vector<Action>( );
	private List<Action>      acoesReleased = new Vector<Action>( );
	
	private TecladoAdapter( ) { }
	
	/* (non-Javadoc)
	 * @see java.awt.event.KeyAdapter#keyPressed(java.awt.event.KeyEvent)
	 */
	public void keyPressed( KeyEvent e ) 
	{
		lEventos.forEach( evento -> 
		{
			if( e.getKeyCode( ) == evento.getKeyCode( ) )
			{
				evento.setTimeDispared( System.currentTimeMillis( ) );
				
				for( Action item : acoesPressed )
					item.executa( evento );
			}
		} );
	}
	
	@Override
	public void keyReleased( KeyEvent e ) 
	{
		lEventos.forEach( evento -> 
		{
			if( e.getKeyCode( ) == evento.getKeyCode( ) )
			{
				evento.setTimeDispared( System.currentTimeMillis( ) );
				
				for( Action item : acoesReleased )
					item.executa( evento );
			}
		} );
	}
	
	public void addOnPressed( Action acao )
	{
		acoesPressed.add( acao );
	}
	
	public void addOnReleased( Action acao )
	{
		acoesReleased.add( acao );
	}

	public void addkeyTiger( EventoTecla e ) 
	{
		lEventos.add( e );
	}

	public void dispose( )
	{
	    Tela.getTela( ).removeKeyListener( this );
	}
	
	public static TecladoAdapter infNewInstacia( )
	{
		TecladoAdapter tecladoAdapter = new TecladoAdapter( );
		
		Tela.getTela( ).addKeyListener( tecladoAdapter );
		
		for( TecladoAdapter item : lInstancias )
        {
		    item.dispose( );
        }
		
		lInstancias.clear( );
		
		lInstancias.add( tecladoAdapter );
		    
		return tecladoAdapter;
	}
}